package com.gaga.common.utils;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.UGen;
import net.beadsproject.beads.core.io.JavaSoundAudioIO;
import net.beadsproject.beads.data.Sample;
import net.beadsproject.beads.ugens.BiquadFilter;
import net.beadsproject.beads.ugens.Gain;
import net.beadsproject.beads.ugens.SamplePlayer;

import java.util.ArrayList;
import java.util.List;

public class EightBandEqualizer {

    // 8个频段的中心频率（与UI对应）
    private static final float[] FREQUENCIES = {
            115, 240, 455, 800, 2000, 4500, 9000
    };

    private AudioContext ac;
    private SamplePlayer player;
    private List<BiquadFilter> filters = new ArrayList<>();
    private Gain masterGain;

    public EightBandEqualizer(String audioPath) {
        ac = new AudioContext(new JavaSoundAudioIO(512));

        try {
            // 加载音频
            Sample sample = new Sample(audioPath);
            player = new SamplePlayer(ac, sample);
            player.setLoopType(SamplePlayer.LoopType.NO_LOOP_FORWARDS);

            // 初始化8段滤波器
            createFilters();

            // 创建主音量控制
            masterGain = new Gain(ac, 2, 1.0f);

            // 构建音频链：播放器 -> 各滤波器并联 -> 主音量 -> 输出
            UGen lastNode = player;
            for (BiquadFilter filter : filters) {
                filter.addInput(lastNode);
                lastNode = filter;
            }
            masterGain.addInput(lastNode);
            ac.out.addInput(masterGain);
            ac.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createFilters() {
        for (float freq : FREQUENCIES) {
            BiquadFilter filter = new BiquadFilter(ac, 2, BiquadFilter.Type.PEAKING_EQ);
            filter.setFrequency(freq)
                    .setQ(1.0f)    // Q值可根据需求调整
                    .setGain(0.0f); // 默认增益0dB
            filters.add(filter);
        }
    }

    // 设置指定频段的增益（bandIndex: 0-6）
    public void setBandGain(int bandIndex, float gainDB) {
        if (bandIndex >= 0 && bandIndex < filters.size()) {
            filters.get(bandIndex).setGain(gainDB);
        }
    }

    // 恢复默认值（所有增益归零）
    public void resetToDefault() {
        filters.forEach(filter -> filter.setGain(0.0f));
    }

    // 主音量控制
    public void setMasterVolume(float volume) {
        masterGain.setGain(volume);
    }
}